package io.plus.user_interface.io.server.command.command_handler;

import io.plus.interactive.AsynchronousSocketChannelContext;
import io.plus.user_interface.io.common.io;
import io.plus.user_interface.io.common.packet.ChatMessage;
import io.plus.user_interface.io.common.packet.ChatType;
import io.plus.user_interface.io.common.packet.Command;
import io.plus.user_interface.io.common.packet.ResponseMessage;
import io.plus.user_interface.io.common.protocol.PacketImpl;
import io.plus.user_interface.io.common.utils.ChatKit;
import io.plus.user_interface.io.server.command.AbstractCommandHandler;

/**
 * 聊天请求cmd消息命令处理器
 */
public class ChatReqHandler extends AbstractCommandHandler {

    @Override
    public Command command() {
        return Command.chat_request;
    }

    @Override
    public PacketImpl handler(PacketImpl packet, AsynchronousSocketChannelContext asynchronousSocketChannelContext) throws Exception {
        if (packet.getBody() == null) {
            throw new Exception("body is null");
        }
        ChatMessage chatBody = ChatKit.toChatBody(packet.getBody(), asynchronousSocketChannelContext);
        packet.setBody(chatBody.toByte());
        //聊天数据格式不正确
        if (chatBody == null || chatBody.getChatType() == null) {
            PacketImpl respChatPacket = ChatKit.dataInCorrectRespPacket(asynchronousSocketChannelContext);
            return respChatPacket;
        }


        PacketImpl chatPacket = new PacketImpl(Command.chat_request, new ResponseMessage(Command.chat_request, chatBody).toByte());
        //设置同步序列号;
        chatPacket.setSynSeq(packet.getSynSeq());
        //私聊
        if (ChatType.private_chat.getNumber() == chatBody.getChatType()) {
            String toId = chatBody.getTo();
            if (ChatKit.isOnline(toId, userConfiguration)) {
                io.sendToUser(toId, chatPacket);
                //发送成功响应包
                return ChatKit.sendSuccessRespPacket(asynchronousSocketChannelContext);
            } else {
                //用户不在线响应包
                return ChatKit.offlineRespPacket(asynchronousSocketChannelContext);
            }
            //群聊
        } else if (ChatType.public_chat.getNumber() == chatBody.getChatType()) {
            String group_id = chatBody.getGroupId();
            io.sendToGroup(group_id, chatPacket);
            //发送成功响应包
            return ChatKit.sendSuccessRespPacket(asynchronousSocketChannelContext);
        }
        return null;
    }
}
